package me.techbird.nve.dao.impl;

import me.techbird.nve.dao.UserDao;
import me.techbird.nve.domain.User;
import me.techbird.express.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<User> findByPage(int start, int pageSize) {
        String sql = "select * from tab_user where role = 2 ";
        StringBuilder sb = new StringBuilder(sql);
        List<Integer> params = new ArrayList<>();
        sb.append("limit ? , ?");
        sql = sb.toString();
        params.add(start);
        params.add(pageSize);
        System.out.println(sql + params.toString());
        return template.query(sql, new BeanPropertyRowMapper<User>(User.class),params.toArray());
    }

    @Override
    public int findTotalCount() {
        String sql = "select count(*) from tab_user where role = 2";
        return template.queryForObject(sql, Integer.class);
    }

    @Override
    public int add(User user) {
        String sql = "insert into tab_user(stu_no, password, name, role, major, create_time) values(?,?,?,?,?,?)";
        return template.update(sql, user.getStu_no(), user.getPassword(), user.getName(),user.getRole(),user.getMajor(),new Date());
    }

    @Override
    public int updateUser(User user) {
        String sql = "update tab_user set stu_no=?, password=?, name=?, role=?, major=? where uid=?";
        return template.update(sql, user.getStu_no(),user.getPassword(),user.getName(),user.getRole(),user.getMajor(),user.getUid());
    }

    @Override
    public int removeUserByUid(Integer uid) {
        String sql = "delete from tab_user where uid = ?";
        return template.update(sql,uid);
    }

    @Override
    public User findByStuNoAndPassword(String stu_no, String password){
        User user = null;
        try {
            String sql = "select * from tab_user where stu_no = ? and password = ?";
            user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),stu_no,password);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public List<User> findAllUser() {
        String sql = "select * from tab_user where role = 2";
        return template.query(sql, new BeanPropertyRowMapper<User>(User.class));
    }

    @Override
    public User findByUid(String uid) {
        User user = null;
        try {
            String sql = "select * from tab_user where uid = ?";
            user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),uid);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return user;
    }

}
